package com.jiawen.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

@Configuration
public class MySecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;

    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
            auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder()); //加入一个自定义的认证类
    }

    @Bean
    PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.exceptionHandling().accessDeniedPage("/exception.html");
        http.formLogin() //自定义的登录界面
            .loginPage("/login.html")  //登录的界面配置
            .loginProcessingUrl("/login") //登录访问路径
            .defaultSuccessUrl("/index").permitAll()  //登录成功跳转路径
            .and().authorizeRequests()
                .antMatchers("/","/hello","/login").permitAll() //哪些路径不需要认证，就可以访问
                //方法1
                //.antMatchers().hasAuthority("admin")  //一个权限
                //方法2
                //.antMatchers("/index").hasAnyAuthority("admins","manager") //多个权限
                //方法3
                .antMatchers("/index").hasRole("sales")
            .anyRequest().authenticated()
                .and().csrf().disable();        //关闭csrf防护
    }
}
